#!/bin/bash

# 社交APP部署脚本
# 适用于Ubuntu 20.04 LTS

set -e

echo "=== 社交APP网页端部署脚本 ==="
echo "开始部署..."

# 更新系统
echo "更新系统包..."
sudo apt update && sudo apt upgrade -y

# 安装Node.js 18
echo "安装Node.js 18..."
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# 安装MySQL
echo "安装MySQL..."
sudo apt install -y mysql-server
sudo mysql_secure_installation

# 安装Nginx
echo "安装Nginx..."
sudo apt install -y nginx

# 安装PM2
echo "安装PM2..."
sudo npm install -g pm2

# 创建项目目录
echo "创建项目目录..."
sudo mkdir -p /var/www/html
sudo chown -R $USER:$USER /var/www/html

# 复制文件
echo "复制项目文件..."
cp -r * /var/www/html/
cd /var/www/html

# 安装依赖
echo "安装Node.js依赖..."
npm install

# 配置数据库
echo "配置数据库..."
echo "请输入MySQL root密码:"
read -s mysql_password

sudo mysql -u root -p$mysql_password << EOF
CREATE DATABASE IF NOT EXISTS social_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE social_app;
source social_app_db.sql;
CREATE USER IF NOT EXISTS 'socialapp'@'localhost' IDENTIFIED BY 'socialapp123';
GRANT ALL PRIVILEGES ON social_app.* TO 'socialapp'@'localhost';
FLUSH PRIVILEGES;
EOF

# 创建环境变量文件
echo "创建环境配置..."
cat > .env << EOF
DB_HOST=localhost
DB_USER=socialapp
DB_PASSWORD=socialapp123
DB_NAME=social_app
JWT_SECRET=$(openssl rand -base64 32)
PORT=3000
EOF

# 配置Nginx
echo "配置Nginx..."
sudo cp nginx.conf /etc/nginx/sites-available/socialapp
sudo ln -sf /etc/nginx/sites-available/socialapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

# 启动应用
echo "启动应用..."
pm2 start server.js --name "social-app"
pm2 startup
pm2 save

# 设置文件权限
echo "设置文件权限..."
sudo chmod -R 755 /var/www/html

# 安装SSL证书（需要域名）
echo "SSL证书配置..."
echo "请确保域名已解析到本服务器IP"
echo "运行以下命令获取SSL证书："
echo "sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com"

echo "=== 部署完成！==="
echo "访问地址: http://your-server-ip"
echo "API地址: http://your-server-ip/api"
echo "数据库: social_app"
echo "MySQL用户: socialapp / socialapp123"
echo ""
echo "如需配置域名和HTTPS，请："
echo "1. 将域名解析到服务器IP"
echo "2. 运行: sudo certbot --nginx -d yourdomain.com"
